const Sequelize = require('sequelize');
var config = require('../config');
var init = require('./init.js');

const dataAccess = {
    // 新的数据库访问对象
    // key String 数据库访问类的key
    // option Object 数据库访问类的连接信息
    register: function(key, option) {
        var dbConfig = Object.assign({
            key: key,
            dbName: '',
            userName: '',
            pwd: '',
            host: '',
            port: 3306,
            isShowSql: false
        }, option);
        if (dbConfig.key == "" || dbConfig.dbName == "" ||
            dbConfig.userName == "" || dbConfig.pwd == "" || dbConfig.host == "") {
            throw new Error("错误的数据库配置");
        }
        if (this[dbConfig.key]) {
            throw new Error("已经存在该配置");
        }
        const sequelize = new Sequelize(dbConfig.dbName, dbConfig.userName, dbConfig.pwd, {
            host: dbConfig.host,
            port: dbConfig.port,
            dialect: 'mysql',
            logging: dbConfig.isShowSql, // 是否打印sql到控制台
            timezone: '+08:00',
            pool: {
                max: 5,
                min: 0,
                acquire: 30000,
                idle: 10000
            }
        });
        init(sequelize);
        this[dbConfig.key] = sequelize;
    },
    // 查询是否存在该数据库访问对象
    isExistsByKey: function(key = null) {
        return dataAccess[key] != null;
    }

};
for (var i = 0; i < config.dbConfigs.length; i++) {
    var dbConfig = config.dbConfigs[i];
    const sequelize = new Sequelize(dbConfig.dbName, dbConfig.userName, dbConfig.pwd, {
        host: dbConfig.host,
        port: dbConfig.port,
        dialect: 'mysql',
        logging: dbConfig.isShowSql, // 是否打印sql到控制台
        timezone: '+08:00',
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        }
    });
    init(sequelize);
    dataAccess[dbConfig.key] = sequelize;
    if (i == 0) {
        dataAccess.sequelize = sequelize;
    }
}


module.exports = dataAccess;